package com.security;

import cn.hutool.core.util.StrUtil;
import com.entity.TokenEntity;
import com.entity.UserEntity;
import com.entity.YonghuEntity;
import com.service.TokenService;
import com.service.UserService;
import com.service.YonghuService;
import com.utils.JwtTokenUtil;
import com.utils.R;
import com.utils.ResultCode;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

/**
 * @author t-zhaoheng
 * @since 2022/3/28
 */
@Component
@Slf4j
public class MyAuthenticationSuccessHandler extends
    JSONAuthentication implements AuthenticationSuccessHandler {
  @Resource
  StringRedisTemplate stringRedisTemplate;
  @Resource
  TokenService tokenService;
  @Resource
  YonghuService yonghuService;

  @Resource
  UserService userService;

  // 这里得使用new出来的对象，为什么还有待研究
  JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();

  @Override
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
      Authentication authentication) throws IOException {
    // 获取用户信息，并设置进内存中
    UserDetails userDetails = (UserDetails) authentication.getPrincipal();
    SecurityContextHolder.getContext().setAuthentication(authentication);

//    // 从redis取该用户的token
//    String token = stringRedisTemplate.opsForValue().get("token:" + userDetails.getUsername());
//    // 如果没有token(第一次登录)，或者token过期了，生成新的token，保存到redis
//    if(StrUtil.isEmpty(token) || jwtTokenUtil.isTokenExpired(token)) {
//      token = jwtTokenUtil.generateToken(userDetails);
//      stringRedisTemplate.opsForValue().set("token:"+userDetails.getUsername(), token);
//    }

    // 每次登录都生成新的token
    String token = jwtTokenUtil.generateToken(userDetails);
    // 如果是admin(管理员)
    if(userDetails.getUsername().contains("admin")) {
      UserEntity user = userService.getUser(userDetails.getUsername());
      tokenService.generateToken(user, token);
    } else {
      YonghuEntity yonghu = yonghuService.getYonghu(userDetails.getUsername());
      // 将数据库的用户token信息更新
      tokenService.generateToken(yonghu, token);
    }


    // 设置session
    TokenEntity tokenEntity = tokenService.getTokenEntity(token);
    request.getSession().setAttribute("userId", tokenEntity.getUserid());
    request.getSession().setAttribute("role", tokenEntity.getRole());
    request.getSession().setAttribute("tableName", tokenEntity.getTablename());
    request.getSession().setAttribute("username", tokenEntity.getUsername());

    // 登录成功，返回对象
    this.writeJSON(response, R.ok().put("token", token));
  }
}
